// src/stores/user.js

import { defineStore } from 'pinia';
import { login, register } from '../apis/login'; // 确保这个路径是正确的
import { jwtDecode } from 'jwt-decode';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null, // 将存储 { id, username, identity }
    token: null,
    isAuthenticated: false,
  }),

  actions: {
    async loginUser(userData) {
      try {
        const response = await login(userData); // 调用你的 API
        if (response.code === 200 && response.token) {
          const token = response.token;
          localStorage.setItem('token', token);
          this.token = token;

          // 从 token 解码用户信息或直接使用 API 返回的用户信息
          // 优先使用 API 直接返回的明确的用户信息结构
          // 如果 API 只返回 token，则需要从 token 解码
          let userInfo;
          if (response.data && response.data.user_id && response.data.username && response.data.identity) {
            userInfo = {
              id: response.data.user_id,
              username: response.data.username,
              identity: response.data.identity,
            };
          } else {
            // 如果API响应中没有直接的用户信息，尝试从token解码
            try {
              const decodedToken = jwtDecode(token);
              userInfo = {
                id: decodedToken.user_id, // 确保这些字段名与你的JWT负载一致
                username: decodedToken.username,
                identity: decodedToken.identity,
              };
            } catch (decodeError) {
              console.error('Failed to decode token during login:', decodeError);
              this.logout(); // 解码失败，视为登录失败的一部分
              return { success: false, message: '登录成功但无法解析用户信息' };
            }
          }
          
          // 校验解码或获取到的用户信息是否完整
          if (!userInfo || !userInfo.id || !userInfo.username || !userInfo.identity) {
            console.error('User info incomplete after login:', userInfo);
            this.logout();
            return { success: false, message: '登录成功但用户信息不完整' };
          }

          this.user = userInfo;
          this.isAuthenticated = true;
          // console.log('Login successful, user state set:', this.user);
          return { success: true, user: this.user }; // 返回成功和用户信息
        } else {
          return { success: false, message: response.msg || response.message || '登录失败或未收到Token' };
        }
      } catch (error) {
        console.error('Login API error:', error);
        return { success: false, message: error.message || '登录请求发生错误' };
      }
    },

    async registerUser(userData) {
      try {
        const response = await register(userData); // 调用你的 API
        if (response.code === 200) {
          return { success: true, message: response.msg || '注册成功' };
        }
        return { success: false, message: response.msg || '注册失败' };
      } catch (error) {
        return { success: false, message: error.message || '注册请求发生错误' };
      }
    },

    logout() {
      this.user = null;
      this.token = null;
      this.isAuthenticated = false;
      localStorage.removeItem('token');
      // console.log('User logged out, token removed.');
    },

    checkAuth() {
      // console.log('checkAuth called');
      const tokenFromStorage = localStorage.getItem('token');
      // console.log('Token from localStorage:', tokenFromStorage);

      if (tokenFromStorage) {
        try {
          const decodedToken = jwtDecode(tokenFromStorage);
          // console.log('Decoded token:', decodedToken);

          // 检查 token 是否过期 (exp 是以秒为单位的时间戳)
          if (decodedToken.exp * 1000 < Date.now()) {
            // console.warn('Token expired.');
            this.logout(); // Token 过期，执行登出
            return;
          }

          // Token 有效且未过期，恢复用户信息
          // 确保这些字段名与你的 JWT 负载 (payload) 一致
          if (!decodedToken.user_id || !decodedToken.username || !decodedToken.identity) {
            console.error('Token is missing required user information fields.');
            this.logout();
            return;
          }

          this.token = tokenFromStorage;
          this.user = {
            id: decodedToken.user_id,
            username: decodedToken.username,
            identity: decodedToken.identity,
          };
          this.isAuthenticated = true;
          // console.log('checkAuth: User authenticated, user info restored:', this.user);
        } catch (error) {
          // Token 解码失败或无效
          console.error('Invalid token or failed to decode during checkAuth:', error);
          this.logout(); // 执行登出
        }
      } else {
        // 如果 store 中是登录状态但 localStorage 无 token (理论上不应发生，除非手动清除或 logout 未完全同步)
        if (this.isAuthenticated) {
          // console.log('checkAuth: No token in localStorage, but store was authenticated. Logging out.');
          this.logout();
        }
        // console.log('checkAuth: No token found in localStorage.');
      }
    },
  },

  getters: {
    getUserRoleForGuard: (state) => {
      if (state.user && state.isAuthenticated && state.user.identity) {
        switch (state.user.identity.toUpperCase()) { // 转换为大写以确保一致性
          case 'USER':
            return 'client';
          case 'EMPLOYEE':
            return 'employee';
          case 'ADMIN':
            return 'admin';
          default:
            // console.warn('Unknown user identity in getter:', state.user.identity);
            return null; // 或者一个默认的、无权限的角色
        }
      }
      return null;
    },
  },
});